<?php 
/**
 * common functions
 */


if (!function_exists("object2array")) {
	/**
	 * @param  [type] [description]
	 * @return [obj]
	 */
	function object2array($obj){
		if(is_array($obj)) return $obj;
		$return = array();
		foreach($obj as $k=>$v){
			$return[$k] = $v;
		}
		return $return;
	}
}


if (!function_exists("gearman_client")) {
	/**
	 * @param  [type] [description]
	 * @return [obj]
	 */
	function gearman_client($action = 'auto',$func = 'health_bg_upload'){
		# create our client object
		$gmclient= new GearmanClient();
		# add the default server (localhost)
		$gmclient->addServer();

		$gmclient->doBackground($func, $action);
	}
}


if (!function_exists("C")) {
	/**
	 * @param  [type] [description]
	 * @return [obj]
	 */
	function C($name,$value=null){
		static $config = array();
		if(!is_null($value)){
			$config[$name] = $value;
		}
		if(isset($config[$name])) return $config[$name];
		return;
	}
}

if (!function_exists("get_memcache")) {
	/**
	 * @param  [type] [description]
	 * @return [obj]
	 */
	function get_memcache(){
		static $memcache;
		if($memcache) return $memcache;
		$memcache = new Memcache;
		$memcache->connect('127.0.0.1',11211);
		return $memcache;
	}
}

if (!function_exists("get_s3client")) {
	/**
	 * @param  [type] [description]
	 * @return [obj]
	 */
	function get_s3client(){
		static $s3client = null;
		if(!$s3client){
			require_once rtrim(FCPATH ,'/') . '/vendor/autoload.php';
			// use Aws\Common\Aws;
			$aws =  Aws\Common\Aws::factory(rtrim(FCPATH ,'/') . '/vendor/aws-config.php');

			$client = $aws->get('s3');
			$s3client = $client;
		}

		return $s3client;
	}
}

if (!function_exists("cache_flush")) {
	/**
	 * @param  [type] [description]
	 * @return [array]
	 */
	function cache_flush(){
		$cache = get_memcache();
		$cache->flush();
	}
}

if (!function_exists("cache_set")) {
	/**
	 * @param  [type] [description]
	 * @return [array]
	 */
	function cache_set($key,$value,$ex=120){
		$cache = get_memcache();
		// var_dump($cache->setnx($key,$value));die;
		$cache->add($key,serialize($value),false,$ex);
	}
}

if (!function_exists("cache_get")) {
	/**
	 * @param  [type] [description]
	 * @return [array]
	 */
	function cache_get($key){
		$cache = get_memcache();
		return unserialize($cache->get($key));
	}
}

if (!function_exists("get_redis_cache_obj")) {
	/**
	 * @param  [type] [description]
	 * @return [array]
	 */
	function get_redis_cache_obj(){
		static $redisObj;
		if(!$redisObj){
			$redisObj = new Redis();
			$redisObj->connect('127.0.0.1');
		}
		return $redisObj;
	}
}


if (!function_exists("start_end")) {
	/**
	 * [to test a script's running time]
	 * @param  [type] [description]
	 * @return [array]
	 */
	function start_end($mark){
		static $run_time = array();
		if($mark == 'start'){
			$run_time['start'] = microtime(true);
		}
		if($mark == 'end'){
			if(isset($run_time['start'])){
				return microtime(true) - $run_time['start'];
			}
		}
	}
}



if (!function_exists("start_end")) {
	/**
	 * [to test a script's running time]
	 * @param  [type] [description]
	 * @return [array]
	 */
	function start_end($mark){
		static $run_time = array();
		if($mark == 'start'){
			$run_time['start'] = microtime(true);
		}
		if($mark == 'end'){
			if(isset($run_time['start'])){
				return microtime(true) - $run_time['start'];
			}
		}
	}
}

if (!function_exists("put_log")) {
	/**
	 * [put_log description]
	 * @param  [type] [description]
	 * @return [array]
	 */
	function put_log($file,$data,$mod = FILE_APPEND){

		return file_put_contents($file, $data,$mod);
	}
}



if (!function_exists("get_open_id")) {
	/**
	 * [get_open_id get qq upload interface open id]
	 * @param  [type] [description]
	 * @return [array]
	 */
	function get_open_id($access_token){

		$get_openid_url = "https://graph.qq.com/oauth2.0/me?access_token=";
		$url = $get_openid_url . $access_token;

		$rs = file_get_contents($url);
		preg_match('/.+(\{.*?\}).+/is',$rs,$match);

		$match = $match[1];
		if(!is_json($match)){
			return false;
		}
		$match = json_decode($match);
		if(isset($match->openid)){
			return $match->openid;
		}

		return false;
	}
}

if (!function_exists("jsonObj_to_array")) {
	/**
	 * [jsonObj_to_array description]
	 * @param  [type] [description]
	 * @return [array]
	 */
	function jsonObj_to_array($json){
		if(is_string($json)) return $json;
		$array = array();
		foreach($json as $k=>$v){
			$array[$k] = jsonObj_to_array($v);

		}
		
		return $array;
	}
}


if (!function_exists("is_json")) {
	/**
	 * [is_json description]
	 * @param  [type] [description]
	 * @return [bool]       []
	 */
	function is_json($string){
		json_decode($string);
		return (json_last_error() == JSON_ERROR_NONE);
	}
}



if (!function_exists("read_zip")) {
	/**
	 * [read_zip description]
	 * @param  [type] $file [description]
	 * @return [array]       []
	 */
	function read_zip($file){

		$temp_path = rtrim(FCPATH,'/') . "/../uploads/";
		$zip = new ZipArchive; 
		$res = $zip->open($file);
		if($res == true){
			$i=0;
			$arr = array();
			$zip->extractTo($temp_path);
			while($index = $zip->getNameIndex($i)){
				$file = $temp_path . $index;
				if(is_file($file)){
					$info = pathinfo($file);
					$newFile = $info['dirname'] . '/' . md5(time().$index) . '.' . $info['extension'];
					rename($file, $newFile);
					$arr[] = $newFile;
				}

				if(is_dir($file)){
					remove_directory($file);
				}
				
				$i++;
			}
			$zip->close();
			return $arr;
		}

		return false;

	}
}


if (!function_exists("remove_directory")) {
	/**
	 * function to remove dir
	 * @param  [type] $dir [description]
	 * @return [type]      [description]
	 */
	function remove_directory($dir) {
	  if ($handle = opendir("$dir")) {
	   while (false !== ($item = readdir($handle))) {
	     if ($item != "." && $item != "..") {
	       if (is_dir("$dir/$item")) {
	         remove_directory("$dir/$item");
	       } else {
	         unlink("$dir/$item");
	       }
	     }
	   }
	   closedir($handle);
	   rmdir($dir);
	  }
	}

}

/**
 * [json_return]
 * @param  array  $json [description]
 * @return [type]       [description]
 */
if (!function_exists("json_return")) {
	function json_return($success = false,$info = 'no data'){
		$success = $success == true ? array('success'=>true) : array('success'=>false);
		if(is_string($info)){
			$info = array('info'=>$info);
		}

		if(is_array($info)){
			$data = array_merge($success,$info);
			echo json_encode($data);
			exit;
		}else{
			exit("incorrect params");
		}
		
	}
}


if (!function_exists("post")) {
	/**
	 * [post set a post request ]
	 * @param  [type] $url  [description]
	 * @param  string $data [description]
	 * @return [type]       [description]
	 */
	function post($url,$data=array()){
		if(!$url) return;
		// build post data
	    $data = http_build_query($data);  
	  
	    $opts = array (  
	        'http' => array (  
	        'method' => 'POST',  
	        'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .  
	        "Content-Length: " . strlen($data) . "\r\n",  
	        'content' => $data  
	        )  
	    );  
	  
	    $context = stream_context_create($opts);  
	    return file_get_contents($url, false, $context); 

	}
}

if (!function_exists("dump")) {
	/**
	 * [dump formate print data]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	function dump($data){
		echo '<pre>';
		print_r($data);
		echo '</pre>';
	}
}
